package co.com.impresion.archivos;

import java.applet.Applet;
import java.awt.HeadlessException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.AttributedString;

import co.com.impresion.utils.MessageBundleLoader;

public class Impresion extends Applet implements Runnable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private AttributedString texto;
	private String programa;
	private String path;
	private Thread hilo;
	private String pathServlet;

	private String systemProperty = MessageBundleLoader
			.getMessage("applet.systemProperty.property");
	private String matchesWindows = MessageBundleLoader
			.getMessage("applet.systemProperty.matches");
	private String acceptLanguage = MessageBundleLoader
			.getMessage("applet.requestProperty.accept");
	private String language = MessageBundleLoader
			.getMessage("applet.requestProperty.language");

	/**
	 * Constructor of the applet.
	 * 
	 * @exception HeadlessException
	 *                if GraphicsEnvironment.isHeadless() returns true.
	 */
	public Impresion() throws HeadlessException {
		super();
	}

	/**
	 * Called by the browser or applet viewer to inform this applet that it is
	 * being reclaimed and that it should destroy any resources that it has
	 * allocated. The <code>stop</code> method will always be called before
	 * <code>destroy</code>.
	 * <p>
	 * 
	 * A subclass of <code>Applet</code> should override this method if it has
	 * any operation that it wants to perform before it is destroyed. For
	 * example, an applet with threads would use the <code>init</code> method
	 * to create the threads and the <code>destroy</code> method to kill them.
	 * <p>
	 */
	public void destroy() {
		// Put your code here
	}

	/**
	 * Returns information about this applet. An applet should override this
	 * method to return a <code>String</code> containing information about the
	 * author, version, and copyright of the applet.
	 * <p>
	 * 
	 * @return a string containing information about the author, version, and
	 *         copyright of the applet.
	 */
	public String getAppletInfo() {
		return "This is my default applet created by Eclipse";
	}

	/**
	 * Called by the browser or applet viewer to inform this applet that it has
	 * been loaded into the system. It is always called before the first time
	 * that the <code>start</code> method is called.
	 * <p>
	 * 
	 * A subclass of <code>Applet</code> should override this method if it has
	 * initialization to perform. For example, an applet with threads would use
	 * the <code>init</code> method to create the threads and the
	 * <code>destroy</code> method to kill them.
	 * <p>
	 */
	public void init() {

		if (System.getProperty(systemProperty).matches(matchesWindows)) {
			path = MessageBundleLoader
					.getMessage("path.generacionArchivo.windows");
			programa = (new StringBuilder()).append(
					MessageBundleLoader
							.getMessage("path.programaImresion.windows"))
					.append(path).toString();
		} else {
			path = MessageBundleLoader
					.getMessage("path.generacionArchivo.linux");
			programa = MessageBundleLoader
					.getMessage("path.programaImpresion.linux");
		}
	}

	/**
	 * Called by the browser or applet viewer to inform this applet that it
	 * should start its execution. It is called after the <code>init</code>
	 * method and each time the applet is revisited in a Web page.
	 * <p>
	 * 
	 * A subclass of <code>Applet</code> should override this method if it has
	 * any operation that it wants to perform each time the Web page containing
	 * it is visited. For example, an applet with animation might want to use
	 * the <code>start</code> method to resume animation, and the
	 * <code>stop</code> method to suspend the animation.
	 * <p>
	 */
	public void start() {
		// Put your code here
	}

	/**
	 * Called by the browser or applet viewer to inform this applet that it
	 * should stop its execution. It is called when the Web page that contains
	 * this applet has been replaced by another page, and also just before the
	 * applet is to be destroyed.
	 * <p>
	 * 
	 * A subclass of <code>Applet</code> should override this method if it has
	 * any operation that it wants to perform each time the Web page containing
	 * it is no longer visible. For example, an applet with animation might want
	 * to use the <code>start</code> method to resume animation, and the
	 * <code>stop</code> method to suspend the animation.
	 * <p>
	 */

	public void loadPrint() {
		hilo = new Thread(this);
		hilo.start();
	}

	public void sendParams(URLConnection url) throws IOException {
		url.setDoOutput(true);
		url.setUseCaches(false);
		PrintWriter salida = new PrintWriter(url.getOutputStream());
		salida.close();
	}

	public void receiveResponse(URLConnection url) throws IOException {

		InputStreamReader streamEntrada = new InputStreamReader(url
				.getInputStream());
		BufferedReader bfEntrada = new BufferedReader(streamEntrada);

		PrintStream salida = new PrintStream(new FileOutputStream(
				new File(path)));
		String linea;
		while ((linea = bfEntrada.readLine()) != null)
			salida.println(linea);
		salida.close();
		// Process p = Runtime.getRuntime().exec(programa);
		bfEntrada.close();
	}

	public void stop() {
		// Put your code here
	}

	public AttributedString getTexto() {
		return texto;
	}

	public void setTexto(AttributedString texto) {
		this.texto = texto;
	}

	public void run() {
		// TODO Auto-generated method stub
		try {
			AttributedString texto;
			StringBuffer contenido = new StringBuffer();
			String linea;
			String cadena = getCodeBase().toString();
			cadena = cadena.substring(0, cadena.length() - 6);
			pathServlet = (new StringBuilder()).append(cadena).append(
					MessageBundleLoader
							.getMessage("applet.nombre.servletImpresion"))
					.toString();

			URL urlServlet = new URL(pathServlet);
			URLConnection conServlet = urlServlet.openConnection();
			conServlet.setRequestProperty(acceptLanguage, language);

			sendParams(conServlet);
			receiveResponse(conServlet);

			File f = new File(path);
			FileInputStream fis = new FileInputStream(f);
			InputStreamReader isr = new InputStreamReader(fis);
			BufferedReader br = new BufferedReader(isr);

			while ((linea = br.readLine()) != null) {
				contenido.append(linea);
			}

			texto = new AttributedString(contenido.toString());
			new Impresora().impresionArchivo(path, texto);
		} catch (MalformedURLException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}
